package com.slipper.system.ai.service;

import java.util.List;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;

import com.slipper.system.ai.dao.AiModelDao;
import com.slipper.system.ai.bo.AiModelBO;

import com.slipper.core.transaction.ReadTransactional;
import com.slipper.core.transaction.WriteTransactional;
import com.slipper.util.Tool;
import com.slipper.util.UUID;

@Service
@ReadTransactional
public class AiModelService {
    @Resource
    private AiModelDao aiModelDao;
    
    public AiModelBO queryBy(String id) {
        return aiModelDao.queryBy(id);
    }
    
    public List<AiModelBO> queryList(AiModelBO bo) {
        return aiModelDao.queryList(bo);
    }
    
    public PageInfo<AiModelBO> queryPage(AiModelBO bo) {
        PageHelper.startPage(bo.getPageNumber(), bo.getPageSize());
        return new PageInfo<>(aiModelDao.queryList(bo));
    }
    
    @WriteTransactional
    public int save(AiModelBO bo) {
        if (Tool.isNotBlank(bo.getId())) {
            bo.setUpdateTime(System.currentTimeMillis());
            return aiModelDao.update(bo);
        } else {
            bo.setId(UUID.getUUID());
            bo.setUpdateTime(System.currentTimeMillis());
            bo.setCreateTime(System.currentTimeMillis());
            return aiModelDao.insert(bo);
        }
    }

    @WriteTransactional
    public void saveList(List<AiModelBO> list) {
        if (list == null) return;

        list.forEach(item -> {
            if (aiModelDao.queryBy(item.getId()) != null) {
                item.setUpdateTime(System.currentTimeMillis());
                aiModelDao.update(item);
            } else {
                item.setUpdateTime(System.currentTimeMillis());
                item.setCreateTime(System.currentTimeMillis());
                aiModelDao.insert(item);
            }
        });
    }
    
    @WriteTransactional
    public int delete(AiModelBO bo) {
        return aiModelDao.delete(bo);
    }

    public AiModelBO queryDefaultChatModel() {
        AiModelBO qo = new AiModelBO();
        qo.setSupplierModelType(AiModelBO.CHAT_MODEL);
        PageHelper.startPage(1, 1);
        PageInfo<AiModelBO> pageInfo = new PageInfo<>(aiModelDao.queryList(qo));
        return pageInfo.getList().isEmpty() ? null : pageInfo.getList().getFirst();
    }
}
